<?php
/**
 * Created by PhpStorm.
 * User: yys
 * Date: 2016/12/5
 * Time: 17:36
 */

namespace App\Services\TagService;


use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Validator;
class TagTool
{
    /***
     * 是否有子标签
     * @param $tag_id
     * @param int $state
     * @return bool
     */
    public static function hasSubTagByTagId($tag_id,$state=1){
        if(empty($tag_id)||(!is_int($tag_id))){
            return false;
        }
        if($state===1){
            $num=DB::table('tag_sub_tag_maps')
                ->where(array(
                    'tag_id'=>$tag_id,
                    'state'=>1
                ))->count();
        }else{
            $num=DB::table('tag_sub_tag_maps')
                ->where(array(
                    'tag_id'=>$tag_id,
                ))->count();
        }
        return ($num===0)?false:true;
    }

    /***
     * 获取绑定有子标签的标签
     * @param int $state
     * @return array
     */
    public static function getTagIdsHasSubTag($state=1){
        if($state===1){
            $tag_ids=DB::table('tag_sub_tag_maps')
                ->where(array(
                    'state'=>1,
                ))
                ->pluck('tag_id')
                ->toArray();
        }else{
            $tag_ids=DB::table('tag_sub_tag_maps')
                ->pluck('tag_id')
                ->toArray();
        }
        return empty($tag_ids)?array():$tag_ids;
    }

    /***
     * 获取标签下绑定资源
     * @param $tag_id
     * @param int $state
     * @return array
     */
    public static function getResourceIdsByTagId($tag_id,$app_id=1,$state=1){
        if($state===1){
            $resource_ids=DB::table('tag_resource_maps')
                ->where(array(
                    'state'=>1,
                    'app_id'=>$app_id,
                    'tag_id'=>$tag_id,
                ))
                ->pluck('resource_id')
                ->toArray();
        }else{
            $resource_ids=DB::table('tag_resource_maps')
                ->where(array(
                    'app_id'=>$app_id,
                    'tag_id'=>$tag_id,
                ))->pluck('resource_id')
                ->toArray();
        }
        return empty($resource_ids)?array():$resource_ids;
    }

    /***
     * 资源Id获取标签Id
     * @param $resource_id
     * @param int $app_id
     * @param int $state
     * @return int
     */
    public static function getTagIdByResourceId($resource_id,$app_id=1,$state=1){
        $query =DB::table('tag_resource_maps')
            ->where(array(
                'app_id'=>$app_id,
                'resource_id'=>$resource_id,
            ));

        if($state===1){
            $query->where('state',1);
        }
        $tag_id=$query->value('tag_id');
        return empty($tag_id)?0:$tag_id;
    }
    /***
     * 子标签绑定的标签列表
     * @param $tag_id
     * @param int $state
     * @return bool
     */
    public static function hasBindingTagByTagId($tag_id,$state=1){
        if(empty($tag_id)||(!is_int($tag_id))){
            return false;
        }
        if($state===1){
            $num=DB::table('tag_sub_tag_maps')
                ->where(array(
                    'sub_tag_id'=>$tag_id,
                    'state'=>1
                ))->count();
        }else{
            $num=DB::table('tag_sub_tag_maps')
                ->where(array(
                    'sub_tag_id'=>$tag_id,
                ))->count();
        }
        return ($num===0)?false:true;
    }
    /***
     * 获取标签
     * @param $tag_id
     * @param int $state
     * @return array
     */
    public static function getTagIdsBySubTagId($sub_tag_id,$state=1){
        if(empty($sub_tag_id)||(!is_int($sub_tag_id))){
            return array();
        }
        $query=DB::table('tag_sub_tag_maps')
            ->where(array(
                'sub_tag_id'=>$sub_tag_id,
            ));
        if($state===1){
            $query->where('state',1);
        }
        $tag_ids=$query->pluck('tag_id')
                       ->toArray();
        return empty($tag_ids)?array():$tag_ids;
    }

    /***
     * 获取可以直接绑定资源的资源标签
     * @param int $state
     * @param $app_id
     * @return array
     */
    public static function getResourceTagIds($state=1,$app_id){
        $has_sub_tag_tag_ids=self::getTagIdsHasSubTag($state);
        if(empty($tag_ids)){
            $tag_ids=DB::table('tags')
                ->where(array(
                    'state'=>1,
                    'tag_type'=>2,
                    'app_id'=>$app_id,
                ))
                ->pluck('id')
                ->toArray();
        }else{
            $tag_ids=DB::table('tags')
                ->where(array(
                    'state'=>1,
                    'tag_type'=>2,
                    'app_id'=>$app_id,
                ))
                ->whereNotIn('id',$has_sub_tag_tag_ids)
                ->pluck('id')
                ->toArray();
        }
        return empty($tag_ids)?array():$tag_ids;
    }

    /***
     * tag_id获取tag名称
     * @param $tag_id
     * @param int $state
     * @return string
     */
    public static function getTagNameByTagId($tag_id,$state=1){
        if(empty($tag_id)||(!is_int($tag_id))){
            return '';
        }
        if($state===1){
            $name=DB::table('tags')
                ->where(array(
                    'id'=>$tag_id,
                    'state'=>1
                ))->value('name');
        }else{
            $name=DB::table('tags')
                ->where(array(
                    'id'=>$tag_id,
                ))->value('name');
        }
        return empty($name)?'':$name;
    }

    /***
     * 获取有子tag的tag_id数组
     * @param $tag_id
     * @param int $state
     * @return array
     */
    public static function getSubTagIdsByTagId($tag_id,$state=1){
        if(empty($tag_id)||(!is_int($tag_id))){
            return array();
        }
        if($state===1){
            $sub_tag_ids=DB::table('tag_sub_tag_maps')
                ->where(array(
                    'tag_id'=>$tag_id,
                    'state'=>1
                ))->pluck('sub_tag_id')
            ->toArray();
        }else{
            $sub_tag_ids=DB::table('tag_sub_tag_maps')
                ->where(array(
                    'tag_id'=>$tag_id,
                ))->pluck('sub_tag_id')
                ->toArray();
        }
        return empty($sub_tag_ids)?array():$sub_tag_ids;
    }

    /***
     * 获取已经绑定资源的tag_id
     * @param $tag_id
     * @param $app_id
     * @param int $state
     * @return array
     */
    public static function theTagIdsOfTheBoundResource($app_id,$state=1){
        if(empty($app_id)){
            return array();
        }
        $query=DB::table('tag_resource_maps')
            ->where(array(
                'app_id'=>$app_id,
            ));
        if($state===1){
            $query->where('state',1);
        }
        $tag_ids=$query->distinct()
            ->pluck('tag_id')
            ->toArray();
        return empty($tag_ids)?array():$tag_ids;
    }
    /***
     * 保存标签和资源关联
     * @param array $data
     * @return array|bool
     */
    public static function saveTagResourceMaps(array $data){
        try{
        if(empty($data)){
            return array();
        }
        $tag_id=$data['tag_id'];
        $resource_id=$data['resource_id'];
        $app_id=$data['app_id'];
        $data['updated_at']=time();
        $data['state']=1;
        $tag_resource_map_exist=self::tagResourceMapsExistByTagIdAndResourceId($tag_id,$resource_id,0);
        if($tag_resource_map_exist){
            $num=DB::table('tag_resource_maps')
                ->where(array(
                    'tag_id'=>$tag_id,
                    'app_id'=>$app_id,
                    'resource_id'=>$resource_id,
                ))->update($data);
        }else{
            $data['created_at']=time();
            $num=DB::table('tag_resource_maps')->insert($data);
        }
            return ($num===0)?false:true;
        }catch (\Exception $e){
            Log::info($e);
            return false;
        }
    }

    /***
     * 判断标签Id有没有绑过资源
     * @param $tag_id
     * @param $resource_id
     * @param int $state
     * @return bool
     */
    public static function tagResourceMapsExistByTagIdAndResourceId($tag_id,$resource_id,$state=1){
        try{
            if(empty($tag_id)||empty($resource_id)||!is_int($state)){
                return false;
            }
            $query=DB::table('tag_resource_maps')
                ->where(array(
                    'tag_id'=>$tag_id,
                    'resource_id'=>$resource_id,
                ));
            if($state===1){
              $query->where('state',1);
            }
            $num=$query->count();
            return ($num===0)?false:true;
        }catch (\Exception $e){
            Log::info($e);
            return false;
        }
    }

    /***
     * 查询tag_resource_maps是不是存在
     * @param $id
     * @param int $state
     * @return bool
     */
    public static function tagResourceMapIdExistById($id,$state=1){
        try{
            if(empty($id)||!is_int($state)){
                return false;
            }
            $query=DB::table('tag_resource_maps')
                ->where(array(
                    'id'=>$id,
                ));
            if($state===1){
                $query->where('state',1);
            }
            $num=$query->count();
            return ($num===0)?false:true;
        }catch (\Exception $e){
            Log::info($e);
            return false;
        }
    }

    /***
     * 资源Id获取绑定的资源标签Id数组
     * @param $resource_id
     * @param int $state
     * @return array|bool
     */
    public static function getTagIdsByResourceId($resource_id,$app_id,$state=1){
        try{
            if(empty($resource_id)||!is_int($state)||!is_int($app_id)){
                return array();
            }
            $query=DB::table('tag_resource_maps')
                ->where(array(
                    'resource_id'=>$resource_id,
                    'app_id'=>$app_id,
                ));
            if($state===1){
                $query->where('state',1);
            }
            $tag_ids=$query->pluck('tag_id')->toArray();
            return empty($tag_ids)?array():$tag_ids;
        }catch (\Exception $e){
            Log::info($e);
            return false;
        }
    }
    /***
     * 判断标签名是不是已经存在
     * @param $tag_name
     * @param $app_id
     * @param int $state
     * @return bool
     */
    public static function tagNameExistByTagNameAndAppId($tag_name,$app_id,$state=1){
        $tag_name=trim($tag_name);
        if(empty($tag_name)||empty($app_id)){
            return false;
        }
        if($state===1){
            $num=DB::table('tags')
                ->where(array(
                    'app_id'=>$app_id,
                    'name'=>$tag_name,
                    'state'=>1
                ))->count();
        }else{
            $num=DB::table('tags')
                ->where(array(
                    'name'=>$tag_name,
                    'app_id'=>$app_id,
                ))->count();
        }
        return ($num===0)?false:true;
    }

    /***
     * 判断标签是不是存在
     * @param $tag_name
     * @param $app_id
     * @param int $state
     * @return bool
     */
    public static function tagExistByTagIdAndAppId($tag_id,$app_id,$state=1){
        if(empty($tag_id)||empty($app_id)){
            return false;
        }
        if($state===1){
            $num=DB::table('tags')
                ->where(array(
                    'id'=>$tag_id,
                    'app_id'=>$app_id,
                    'state'=>1
                ))->count();
        }else{
            $num=DB::table('tags')
                ->where(array(
                    'id'=>$tag_id,
                    'app_id'=>$app_id,
                ))->count();
        }
        return ($num===0)?false:true;
    }

    /***
     * 查看标签是不是存在
     * @param $tag_id
     * @param int $state
     * @return bool
     */
    public static function tagExistByTagId($tag_id,$state=1){
        if(empty($tag_id)||!is_int($tag_id)){
            return false;
        }
        $query=DB::table('tags')
            ->where(array(
                'id'=>$tag_id,
            ));
        if($state===1){
            $query->where('state',1);
        }
        $num=$query->count();
        return ($num===0)?false:true;
    }

    /***
     *  判断标签和资源绑定是不是存在
     * @param $id
     * @param int $state
     * @return bool
     */
    public static function tagResourceMapExistById($id,$state=1){
        if(empty($id)||!is_int($id)){
            return false;
        }
        $query=DB::table('tag_resource_maps')
            ->where(array(
                'id'=>$id,
            ));
        if($state===1){
            $query->where('state',1);
        }
        $num=$query->count();
        return ($num===0)?false:true;
    }
    /***
     * 删除资源标签关联
     * @param $resource_id
     * @param $app_id
     * @return bool
     */
    public function delTagResourceMapsByResourceId($resource_id,$app_id){
           if(empty($resource_id)||empty($app_id)){
               return false;
           }
        $num=DB::table('tag_resource_maps')
            ->where(array(
                'resource_id'=>$resource_id,
                'app_id'=>$app_id,
                'state'=>1
            ))->update(array(
                'state'=>0,
                'updated_at'=>time(),
            ));
           return ($num===0)?false:true;
    }

    /***
     * 查看标签和子标签是否已经绑定
     * @param $tag_id
     * @param $sub_tag_id
     * @param int $state
     * @return bool
     */
    public static function tagSubTagMapsRecordExistByTagIdAndSubTagId($tag_id,$sub_tag_id,$state=1){
        if(empty($tag_id)||empty($sub_tag_id)){
            return false;
        }
        if($state===1){
            $num=DB::table('tag_sub_tag_maps')
                ->where(array(
                    'tag_id'=>$tag_id,
                    'sub_tag_id'=>$sub_tag_id,
                    'state'=>1
                ))->count();
        }else{
            $num=DB::table('tag_sub_tag_maps')
                ->where(array(
                    'tag_id'=>$tag_id,
                    'sub_tag_id'=>$sub_tag_id,
                ))->count();
        }
        return ($num===0)?false:true;
    }
    /***
     * 判断标签名除当前Id是不是已经存在
     * @param $tag_name
     * @param $app_id
     * @param $id
     * @param int $state
     * @return bool
     */
    public static function tagNameExistByTagNameAndAppIdNotCurrentId($tag_name,$app_id,$id,$state=1){
        $tag_name=trim($tag_name);
        if(empty($tag_name)||empty($app_id)){
            return false;
        }
        $query=DB::table('tags')
            ->where(array(
                'app_id'=>$app_id,
                'name'=>$tag_name
            ));
        if($state===1){
            $query->where('state',1);
        }
        $query->where('id','<>',$id);
        $num=$query->count();
        return ($num===0)?false:true;
    }
    /**
     * 数据验证
     * @param Request $request
     * @param $check_data
     * @return mixed
     */
    public static function store(Request $request,$check_data)
    {
        $v = Validator::make($request->all(), $check_data);
        return $v;
    }

    /***
     * 分页获取标签
     * @param array $data
     * @return null
     */
    public static function pagedAccessToTags(array  $data){
        try{
        $per_page=(!isset($data['per_page'])||!is_int($data['per_page']))?10:$data['per_page'];
        $query=DB::table('tags')->where(array('state'=>1));
        if(isset($data['where'])&&(is_array($data['where']))){
            $query->where($data['where']);
        }
        $query->orderBy('tag_type','ASC');
        $query->orderBy('sort','ASC');
        $query->orderBy('updated_at','DESC');
        return $query->paginate($per_page);
        }catch (\Exception $e){
            Log::info($e);
            return null;
        }
    }

    /***
     * 获取标签详情
     * @param array $data
     * @return null
     */
    public static function getTagByTagId(array  $data){
        try{
            $tag_id=$data['tag_id'];
            $app_id=isset($data['app_id'])?$data['app_id']:1;
            $query=DB::table('tags')->where(array('state'=>1,'id'=>$tag_id));
            $query->where('app_id',$app_id);
            return $query->first();
        }catch (\Exception $e){
            Log::info($e);
            return null;
        }
    }

    /***
     * app_id获取app_name
     * @param $app_id
     * @return string
     */
    public static function getAppNameByAppId($app_id){
        if(!is_int($app_id)||$app_id<0){
            return '';
        }
        $app_name='';
        switch($app_id){
            case 1:
                $app_name='素材';
                break;
            case 2:
                $app_name='产品模板';
                break;
            default:
                break;
        }
        return $app_name;
    }

    /****
     * 资源是否绑定标签
     * @param $tag_id
     * @param $app_id
     * @param $resource_id
     * @param $type
     * @param int $state
     * @return bool
     */
    public static function resourceIdHasBindingTagId($tag_id,$app_id,$resource_id,$state=1)
    {
        $query=DB::table('tag_resource_maps');
        $query->where(array(
            'tag_id'=>$tag_id,
            'app_id'=>$app_id,
            'resource_id'=>$resource_id
        ));
        if($state===1){
            $query->where('state',1);
        }
        $num=$query->count();
        return ($num==0)?false:true;
    }

    /***
     * 删除某一资源下所有绑定
     * @param $resource_id
     * @return bool
     */
    public static function delResourceInTagsByResourceId($resource_id,$app_id=1){
        $resource_id=trim($resource_id);
        $query=DB::table('tag_resource_maps');
        $query->where(array(
            'state'=>1,
            'app_id'=>$app_id,
            'resource_id'=>$resource_id
        ));
        $res=$query->update(array(
            'state'=>0,
            'updated_at'=>time()
        ));
        return empty($res)?false:true;
    }

    /**
     * app_id获取特殊标签id数组，一般是包含全部的
     * @param int $app_id
     * @return array
     */
    public static function getSpecialTagIdsByAppId($app_id=1){
        if(!is_array($app_id)){
            return array();
        }
        $query=DB::table('tags');
        $query->where(array(
            'app_id'=>$app_id,
            'state'=>1
        ));
        $tag_ids=$query->pluck('id')->toArray();
        return empty($tag_ids)?array():$tag_ids;
    }
}